package com.atguigu.gmall.list.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.list.dao.GoodsDao;
import com.atguigu.gmall.list.service.ListService;
import com.atguigu.gmall.model.list.*;
import com.atguigu.gmall.model.product.BaseCategoryView;
import com.atguigu.gmall.model.product.BaseTrademark;
import com.atguigu.gmall.model.product.SkuAttrValue;
import com.atguigu.gmall.model.product.SkuInfo;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.range.Range;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ListServiceImpl implements ListService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private GoodsDao goodsDao;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private RedisTemplate redisTemplate;

    //导入索引
    @Override
    public void upperGoods(Long skuId) {

        //一部手机的全部数据
        Goods goods = new Goods();

        //获取数据
        //1.根据skuId查询SkuInfo信息
        SkuInfo skuInfo = productFeignClient.getSkuInfo(skuId);
        goods.setId(skuInfo.getId());
        goods.setDefaultImg(skuInfo.getSkuDefaultImg());
        goods.setTitle(skuInfo.getSkuName());
        goods.setPrice(skuInfo.getPrice().doubleValue());
        goods.setCreateTime(new Date());

        //2.根据tmId查询品牌相关数据
        BaseTrademark baseTrademark = productFeignClient.getBaseTrademark(skuInfo.getTmId());
        goods.setTmId(baseTrademark.getId());
        goods.setTmName(baseTrademark.getTmName());
        goods.setTmLogoUrl(baseTrademark.getLogoUrl());

        //3.根据category3Id查询分类视图
        BaseCategoryView baseCategoryView = productFeignClient
                .getBaseCategoryView(skuInfo.getCategory3Id());
        goods.setCategory1Id(baseCategoryView.getCategory1Id());
        goods.setCategory1Name(baseCategoryView.getCategory1Name());
        goods.setCategory2Id(baseCategoryView.getCategory2Id());
        goods.setCategory2Name(baseCategoryView.getCategory2Name());
        goods.setCategory3Id(baseCategoryView.getCategory3Id());
        goods.setCategory3Name(baseCategoryView.getCategory3Name());

        //4.根据skuId 查询sku_attr_value  base_attr_info  base_attr_value
        List<SkuAttrValue> skuAttrValueList = productFeignClient.getSkuAttrValue(skuId);
        List<SearchAttr> searchAttrList = skuAttrValueList.stream().map(skuAttrValue -> {
            SearchAttr searchAttr = new SearchAttr();
            searchAttr.setAttrId(skuAttrValue.getBaseAttrInfo().getId());
            searchAttr.setAttrName(skuAttrValue.getBaseAttrInfo().getAttrName());
            searchAttr.setAttrValue(skuAttrValue.getBaseAttrValue().getValueName());
            return searchAttr;
        }).collect(Collectors.toList());
        goods.setAttrs(searchAttrList);
        //保存索引库
        goodsDao.save(goods);
    }

    //删除索引
    @Override
    public void lowerGoods(Long skuId) {
        //ES官方高级删除方式
        /*DeleteRequest deleteRequest = new DeleteRequest();
        deleteRequest.index("goods");
        deleteRequest.id(skuId.toString());
        try {
            restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }*/

        //SpringDataES 删除方式
        goodsDao.deleteById(skuId);
    }

    //增加热度评分
    @Override
    public void hotScore(Long skuId) {
        //0.通过缓存进行缓冲   设置更新规则，不频繁的进行更新（ES的增删改效率低)
        //incrementScore:追加 1：追加的分
        Double hotScore = redisTemplate.opsForZSet().incrementScore("hotScore", skuId, 1);
        //opsForZSet  redis的有序集合
        if (hotScore % 10 == 0){
            //1.查询ES库 此商品的评分
            Optional<Goods> byId = goodsDao.findById(skuId);
            Goods goods = byId.get();
            //2.将此评分加分
            goods.setHotScore(Math.round(hotScore));
            //3.此商品保存回ES库
            goodsDao.save(goods);
        }
    }

    //开始搜索
    @Override
    public SearchResponseVo search(SearchParam searchParam) {
        SearchResponseVo vo = null;

        try {
            //1.构建搜索请求对象
            SearchRequest searchRequest = buildSearchRequest(searchParam);
            //2.执行搜索
            SearchResponse searchResponse = restHighLevelClient
                    .search(searchRequest, RequestOptions.DEFAULT);
            //3.解析结果对象
            vo = parseSearchResponse(searchResponse);
            //当前页
            vo.setPageNo(searchParam.getPageNo());
            //每页数
            vo.setPageSize(searchParam.getPageSize());
            //总页数 = (总条数 + 每页数 -1)/每页数
            vo.setTotalPages((vo.getTotal() + vo.getPageSize() - 1) / vo.getPageSize());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return vo;
    }

    //解析结果
    private SearchResponseVo parseSearchResponse(SearchResponse searchResponse) {
        SearchResponseVo vo = new SearchResponseVo();
        SearchHits hits = searchResponse.getHits();

        Map<String, Aggregation> stringAggregationMap = searchResponse.getAggregations().asMap();

        //解析平台属性
        ParsedNested aggAttrs = (ParsedNested)stringAggregationMap.get("aggAttrs");
        ParsedLongTerms aggAttrId = aggAttrs.getAggregations().get("aggAttrId");
        List<SearchResponseAttrVo> attrsList = aggAttrId.getBuckets().stream().map(bucket -> {
            SearchResponseAttrVo attrVo = new SearchResponseAttrVo();
            //平台属性id
            attrVo.setAttrId(Long.parseLong(bucket.getKeyAsString()));
            //平台属性名称
            ParsedStringTerms aggAttrName = ((Terms.Bucket) bucket).getAggregations().get("aggAttrName");
            attrVo.setAttrName(aggAttrName.getBuckets().get(0).getKeyAsString());
            //平台属性值
            ParsedStringTerms aggAttrValue = ((Terms.Bucket) bucket).getAggregations().get("aggAttrValue");
            List<String> attrValueList = aggAttrValue.getBuckets().stream()
                    .map(Terms.Bucket::getKeyAsString).collect(Collectors.toList());
            attrVo.setAttrValueList(attrValueList);
            return attrVo;
        }).collect(Collectors.toList());

        vo.setAttrsList(attrsList);

        ParsedLongTerms aggTmId = (ParsedLongTerms)stringAggregationMap.get("aggTmId");
        //解析品牌集合
        List<SearchResponseTmVo> trademarkList =
                aggTmId.getBuckets().stream().map(bucket -> {
                    SearchResponseTmVo tmVo = new SearchResponseTmVo();
                    tmVo.setTmId(Long.parseLong(bucket.getKeyAsString()));
                    //品牌名称
                    ParsedStringTerms aggTmName = ((Terms.Bucket) bucket).getAggregations().get("aggTmName");
                    tmVo.setTmName(aggTmName.getBuckets().get(0).getKeyAsString());
                    //品牌的Logo
                    ParsedStringTerms aggTmLogoUrl = ((Terms.Bucket) bucket).getAggregations().get("aggTmLogoUrl");
                    tmVo.setTmLogoUrl(aggTmLogoUrl.getBuckets().get(0).getKeyAsString());
                    return tmVo;
                }).collect(Collectors.toList());
        vo.setTrademarkList(trademarkList);

        //商品结果集
        SearchHit[] hits1 = hits.getHits();

        List<Goods> goodsList = Arrays.stream(hits1).map(hit->{

            Goods goods = JSONObject.parseObject(hit.getSourceAsString(), Goods.class);

            //解析高亮的值
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (null != highlightFields && highlightFields.size()>0){
                HighlightField title = highlightFields.get("title");
                if (title != null){
                    String hname = title.fragments()[0].toString();
                    goods.setTitle(hname);
                    System.out.println(hname);
                }
            }

            return goods;
        }).collect(Collectors.toList());
        vo.setGoodsList(goodsList);

        //分页  总条数
        vo.setTotal(hits.getTotalHits());
        System.out.println(hits.getTotalHits());

        return vo;
    }

    //构建搜索请求对象
    private SearchRequest buildSearchRequest(SearchParam searchParam) {

        //条件对象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        //当多个条件的时候  组合条件对象
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        //搜索关键词  类似于手机，大米，海鲜之类的
        String keyword = searchParam.getKeyword();
        if (!StringUtils.isEmpty(keyword)){
            boolQueryBuilder.must(QueryBuilders.matchQuery("title",keyword)
            .operator(Operator.AND));//must是必须有
        } else {
            //搜索全部数据
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        }
        //品牌  过滤条件
        String trademark = searchParam.getTrademark();
        if (!StringUtils.isEmpty(trademark)){
            String[] t = StringUtils.split(trademark, ":");
            boolQueryBuilder.filter(QueryBuilders.termQuery("tmId",t[0]));
        }
        //一二三级分类
        Long category1Id = searchParam.getCategory1Id();
        if (category1Id != null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("category1Id",category1Id));
        }
        Long category2Id = searchParam.getCategory2Id();
        if (category2Id != null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("category2Id",category2Id));
        }
        Long category3Id = searchParam.getCategory3Id();
        if (category3Id != null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("category3Id",category3Id));
        }

        //平台属性  属性值
        //平台属性ID:平台属性值:平台属性名称
        String[] props = searchParam.getProps();
        if (props != null && props.length > 0){
            //父辈
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

            for (String prop : props) {
                String[] p = prop.split(":");
                BoolQueryBuilder subBoolQuery = QueryBuilders.boolQuery();
                subBoolQuery.must(QueryBuilders.termQuery("attrs.attrId",p[0]));
                subBoolQuery.must(QueryBuilders.termQuery("attrs.attrValue",p[1]));
                boolQuery.must(QueryBuilders
                        .nestedQuery("attrs", subBoolQuery, ScoreMode.None));//nestedQuery()嵌套关系，表示一个套一个
            }
            //父辈
            boolQueryBuilder.filter(boolQuery);
        }

        //构建条件对象   只能用一次
        searchSourceBuilder.query(boolQueryBuilder);

        //排序 order  1:asc 或 1:desc ...
        String order = searchParam.getOrder();
        if (!StringUtils.isEmpty(order)) {
            String[] o = order.split(":");
            String field = null;
            switch (o[0]){
                case "1" : field ="hotScore"; break;
                case "2" : field ="price"; break;
            }

            searchSourceBuilder.sort(field,
                    o[1].equalsIgnoreCase(SortOrder.ASC.toString())?SortOrder.ASC:SortOrder.DESC);
        }



        //分页
        Integer pageNo = searchParam.getPageNo();
        Integer pageSize = searchParam.getPageSize();
        searchSourceBuilder.from((pageNo-1)*pageSize);//开始行 limit 开始行 每页数
        searchSourceBuilder.size(pageSize);

        // 高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title")
                .preTags("<span style='color:red'>")
                .postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);


        //品牌聚合
        searchSourceBuilder.aggregation(
                AggregationBuilders.terms("aggTmId").field("tmId")
                        .subAggregation(AggregationBuilders.terms("aggTmName").field("tmName"))
                        .subAggregation(AggregationBuilders.terms("aggTmLogoUrl").field("tmLogoUrl")));

        //平台属性聚合
        searchSourceBuilder.aggregation(
                AggregationBuilders.nested("aggAttrs","attrs")
                        .subAggregation(AggregationBuilders.terms("aggAttrId").field("attrs.attrId")
                        .subAggregation(AggregationBuilders.terms("aggAttrName").field("attrs.attrName"))
                        .subAggregation(AggregationBuilders.terms("aggAttrValue").field("attrs.attrValue"))));

        System.out.println(searchSourceBuilder.toString());


        SearchRequest searchRequest = new SearchRequest();//请求ES
        //设置要搜索的索引库的名称
        searchRequest.indices("goods");
        //searchRequest.types("info");//不重要，可以省略
        //构建搜索条件对象
        searchRequest .source(searchSourceBuilder);
        return searchRequest;
    }
}
